Conditional Statements
⋮
Depending on whether a condition is true or false, conditional statements let you run specific code blocks. If, elif, and else are Python's main conditional statements.
if statement: When a condition is checked by the if statement and found to be True, the corresponding block of code is run.
Example:
x = 10
if x > 5:
print("x is greater than 5")
if-else Statement: when a condition is satisfied a specific code is executed and if the condition false the else block will be executed.
Example:
x = 3
if x > 5:
print("x is greater than 5")
else:
print("x is less than or equal to 5")
if-elif-else Statement: when we need to check for multiple condition, we can use this elif statement.
Example:
x = 7
if x > 10:
print("x is greater than 10")
elif x == 7:
print("x is equal to 7")
else:
print("x is less than 7")
Nested if Statements: If statements can also be nested inside other if or else blocks. More complicated situations are made possible by this.
Example:
x = 8
if x > 5:
if x < 10:
print("x is between 5 and 10")
Switch case: This is an alternate to if elif statement.
Syntax:def switch_case(option):
match option:
case 1:
return "Case 1"
case 2:
return "Case 2"
case 3:
return "Case 3"
case _:
return "Default Case"
# Example usage
result = switch_case(2)
print(result)
def grade_switch(score):
match score:
case score if score >= 90:
return "A"
case score if score >= 80:
return "B"
case score if score >= 70:
return "C"
case score if score >= 60:
return "D"
case _:
return "F"
# Example usage
score = 85
grade = grade_switch(score)
print(f"Grade for score {score}: {grade}")
Comments